Isomorphic Strings
Question
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
Analysis
- 利用两个num(大小256代表所有可能字符的个数),用来记录某种字符上次出现的位置
- num需赋值小于0以避免下标大于等于0的情况
Code
|
|
Word Pattern
Question
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
- pattern =
"abba", str ="dog cat cat dog"should return true. - pattern =
"abba", str ="dog cat cat fish"should return false. - pattern =
"aaaa", str ="dog cat cat dog"should return false. - pattern =
"abba", str ="dog dog dog dog"should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
Analysis
- 蠢蠢的方法
- Map保存char到string的映射,Set用以判断是否有多个char映射到同一个String
- 第一遍遍历保存映射,第二次遍历查看是否有不符合映射标准的,假如有返回false
- LeetCode Discuss
- 思路跟上题一样,保存每个映射对应的上次出现的位置,可以用一个不限定类型的map取代两个map
- map.put的返回值是之前与 key 关联的值,如果没有针对 key 的映射关系,则返回 null
Code
- Version 1
|
|
- Version 2 (Short one)
|
|